package com.market.service.impl;

import com.market.entity.Provider;
import com.market.mapper.ProviderMapper;
import com.market.service.BillService;
import com.market.service.ProviderService;
import com.market.utils.PageResult;
import com.market.utils.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class ProviderServiceImpl implements ProviderService {
    private static final Logger logger = LoggerFactory.getLogger(ProviderServiceImpl.class);

    @Autowired
    private ProviderMapper providerMapper;
    
    @Autowired
    private BillService billService;
    
    @Override
    public List<Provider> findAll() {
        return providerMapper.findAll();
    }

    @Override
    public Provider findById(Long id) {
        return providerMapper.findById(id);
    }

    @Override
    public List<Provider> findByName(String proName) {
        return providerMapper.findByName(proName);
    }
    
    @Override
    public PageResult<Provider> findByPage(String proName, String proCode, Integer currentPage, Integer pageSize) {
        // 计算偏移量
        Integer offset = (currentPage - 1) * pageSize;
        
        // 查询分页数据
        List<Provider> providers = providerMapper.findByPage(proName, proCode, offset, pageSize);
        
        // 查询总记录数
        int totalCount = providerMapper.countByCondition(proName, proCode);
        
        // 返回分页结果
        return new PageResult<>(currentPage, pageSize, (long) totalCount, providers);
    }

    @Override
    public Map<String, Object> add(Provider provider) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查供应商编码是否已存在
        if (isProCodeExists(provider.getProCode())) {
            result.put("flag", false);
            result.put("message", "供应商编码 " + provider.getProCode() + " 已存在，请使用其他编码");
            return result;
        }
        
        // 设置创建时间
        provider.setCreationDate(new java.sql.Timestamp(System.currentTimeMillis()));
        
        // 设置创建者(当前登录用户)
        Long currentUserId = SessionUtil.getCurrentUserId();
        if (currentUserId != null) {
            provider.setCreatedBy(currentUserId);
        } else {
            // 如果无法获取当前用户ID，则设置为默认系统用户ID（例如1）
            provider.setCreatedBy(1L); // 设置默认管理员ID
        }
        
        try {
            int rows = providerMapper.add(provider);
            if (rows > 0) {
                result.put("flag", true);
                result.put("message", "添加供应商成功");
                result.put("data", provider);
            } else {
                result.put("flag", false);
                result.put("message", "添加供应商失败");
            }
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "添加供应商失败: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    public Map<String, Object> update(Provider provider) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查供应商编码是否已存在（排除当前ID）
            if (isProCodeExistsExcludeId(provider.getProCode(), provider.getId())) {
                result.put("flag", false);
                result.put("message", "供应商编码 " + provider.getProCode() + " 已被其他供应商使用，请更换");
                return result;
            }
            
            // 确保有修改者ID
            if (provider.getModifyBy() == null) {
                // 尝试从SessionUtil获取用户ID
                Long currentUserId = SessionUtil.getCurrentUserId();
                if (currentUserId != null) {
                    provider.setModifyBy(currentUserId);
                    logger.info("从SessionUtil获取到修改者ID: {}", currentUserId);
                } else {
                    logger.warn("无法获取当前用户ID，修改者信息将为null");
                }
            } else {
                logger.info("使用请求中提供的修改者ID: {}", provider.getModifyBy());
            }
            
            // 设置修改时间
            provider.setModifyDate(new java.sql.Timestamp(System.currentTimeMillis()));
            logger.info("设置修改时间: {}", provider.getModifyDate());
            
            // 执行更新操作
            int rows = providerMapper.update(provider);
            if (rows > 0) {
                result.put("flag", true);
                result.put("message", "修改供应商成功");
                result.put("data", provider);
                logger.info("供应商更新成功，ID: {}, 修改者: {}, 修改时间: {}", 
                            provider.getId(), provider.getModifyBy(), provider.getModifyDate());
            } else {
                result.put("flag", false);
                result.put("message", "修改供应商失败，可能供应商不存在");
                logger.warn("供应商更新失败，ID: {}", provider.getId());
            }
        } catch (Exception e) {
            logger.error("修改供应商出现异常", e);
            result.put("flag", false);
            result.put("message", "修改供应商失败: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    public Map<String, Object> deleteById(Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查是否有关联的账单
            boolean hasRelatedBills = billService.hasRelatedBills(id);
            if (hasRelatedBills) {
                result.put("flag", false);
                result.put("message", "该供应商存在关联的账单，不能删除");
                return result;
            }
            
            int rows = providerMapper.deleteById(id);
            if (rows > 0) {
                result.put("flag", true);
                result.put("message", "删除供应商成功");
            } else {
                result.put("flag", false);
                result.put("message", "删除供应商失败，可能供应商不存在");
            }
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "删除供应商失败: " + e.getMessage());
        }
        
        return result;
    }
    
    @Override
    public boolean isProCodeExists(String proCode) {
        if (proCode == null || proCode.trim().isEmpty()) {
            return false;
        }
        return providerMapper.findByProCode(proCode) != null;
    }
    
    @Override
    public boolean isProCodeExistsExcludeId(String proCode, Long id) {
        if (proCode == null || proCode.trim().isEmpty() || id == null) {
            return false;
        }
        return providerMapper.findByProCodeExcludeId(proCode, id) != null;
    }
}
